import re
import os
import shutil


def copy_images_from_md(md_file_path):
    """
    从 Markdown 文件中拷贝图片到该文件同级目录下的 output_img 文件夹
    :param md_file_path: Markdown 文件路径
    """
    # 检查 Markdown 文件是否存在
    if not os.path.exists(md_file_path):
        print(f"Markdown 文件 {md_file_path} 不存在。")
        return

    # 获取 Markdown 文件所在目录
    md_dir = os.path.dirname(os.path.abspath(md_file_path))
    # 定义目标文件夹路径
    target_path = os.path.join(md_dir, "output_img")

    # 创建目标文件夹，如果不存在的话
    if not os.path.exists(target_path):
        try:
            os.makedirs(target_path)
        except OSError as e:
            print(f"创建目标文件夹 {target_path} 时出错: {e}")
            return

    try:
        # 读取 Markdown 文件内容
        with open(md_file_path, 'r', encoding='utf-8') as file:
            content = file.read()
    except Exception as e:
        print(f"读取 Markdown 文件 {md_file_path} 时出错: {e}")
        return

    # 匹配 Markdown 中图片的正则表达式，兼容两种格式
    img_pattern = r"!\[.*?\]\((.*?)\)|<img.*?src=[\"'](.*?)[\"'].*?>"
    img_matches = re.findall(img_pattern, content)

    for match in img_matches:
        img_path = next((path for path in match if path), None)
        if img_path:
            full_img_path = os.path.join(md_dir, img_path)
            if os.path.exists(full_img_path):
                file_name = os.path.basename(img_path)
                target_img_path = os.path.join(target_path, file_name)
                try:
                    shutil.copy2(full_img_path, target_img_path)
                    print(f"已将 {full_img_path} 拷贝到 {target_img_path}")
                except Exception as e:
                    print(f"拷贝图片 {full_img_path} 时出错: {e}")
            else:
                print(f"图片 {full_img_path} 不存在，无法拷贝。")


if __name__ == "__main__":
    md_file = r"F:\aaworkspace\zmo_git_space\note\00-seal\03-计算机基础\http请求完整过程.md"
    copy_images_from_md(md_file)
    